package com.zndroid.base.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.zndroid.base.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 页面状态控件
 *
 * @author lzy
 * @date 2021/3/1
 */
@SuppressWarnings("unused")
public class HolderView extends RelativeLayout {
    private LinearLayout tipView;
    
    private List<View> childViews;
    private AlertDialog progressDialog;
    private int emptyImageResId = R.drawable.z_base_ic_empty_data;
    private int badNetResId = R.drawable.z_base_ic_error_net;
    private int errorImageResId = R.drawable.z_base_ic_error_data;
    private int notFoundImageResId = R.drawable.z_base_ic_404;

    private String emptyText = "暂无数据";
    private String badNetText = "网络不稳定，请稍候重试";
    private String notFoundText = "内容不存在，请稍候重试";
    private String errorText = "加载错误，请稍候重试";
    private String loadingText = "";
    
    private int themeColor = -1;
    
    private String retryButtonText = "点我重试";
    private boolean showRetryButton = true;
    private boolean cancelable = false;

    private OnRetryButtonClickListener onRetryButtonClickListener;
    
    public HolderView(Context context) {
        super(context);
        init(context, null);
    }
    
    public HolderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }
    
    public HolderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }
    
    private void init(Context context, AttributeSet attrs) {
        tipView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.z_base_layout_holder_view, null, false);
        tipView.setLayoutParams(new RadioGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        tipView.setVisibility(GONE);
        addView(tipView);
        
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.HolderView);
            emptyText = getResString(typedArray, R.styleable.HolderView_hv_emptyText, emptyText);
            badNetText = getResString(typedArray, R.styleable.HolderView_hv_badNetText, badNetText);
            errorText = getResString(typedArray, R.styleable.HolderView_hv_errorText, errorText);
            
            emptyImageResId = typedArray.getResourceId(R.styleable.HolderView_hv_emptyImageResId, emptyImageResId);
            badNetResId = typedArray.getResourceId(R.styleable.HolderView_hv_badNetResId, badNetResId);
            errorImageResId = typedArray.getResourceId(R.styleable.HolderView_hv_errorImageResId, errorImageResId);
            notFoundImageResId = typedArray.getResourceId(R.styleable.HolderView_hv_notFoundImageResId, notFoundImageResId);

            themeColor = typedArray.getColor(R.styleable.HolderView_hv_themeColor, themeColor);
            
            retryButtonText = getResString(typedArray, R.styleable.HolderView_hv_retryButtonText, retryButtonText);
            showRetryButton = typedArray.getBoolean(R.styleable.HolderView_hv_retryButtonVisibility, showRetryButton);
            typedArray.recycle();
        }
        
        refreshViews();
    }
    
    public void showBadNet() {
        setTipInfo(badNetResId, badNetText, true);
    }
    
    public void showWait() {
        showProgress("", false);
    }

    public void showWait(String msg) {
        showProgress(msg, false);
    }

    public void showWait(String msg, boolean cancelable) {
        showProgress(msg, cancelable);
    }

    public void show404() {
        showTip(notFoundImageResId, notFoundText, true);
    }

    public void show404(String msg, boolean isShowRetry) {
        if (null == msg) {
            show404();
            return;
        }
        showTip(notFoundImageResId, msg, isShowRetry);
    }

    public void showSuccess() {
        dismissProgressDialog();
        showChild(true);
    }
    
    public void showError() {
        setTipInfo(errorImageResId, errorText, true);
    }
    
    public void showEmpty() {
        setTipInfo(emptyImageResId, emptyText, true);
    }
    
    public void showTip(int customImageResId, String text) {
        showTip(customImageResId, text, false);
    }

    public void showTip(int customImageResId, String text, boolean isShowRetry) {
        setTipInfo(customImageResId, text, isShowRetry);
    }
    
    private void setTipInfo(int resId, String text, boolean isShowRetry) {
        ImageView imgViewHolderImage = tipView.findViewById(R.id.base_img_viewHolder_image);
        TextView txtViewHolderTip = tipView.findViewById(R.id.base_txt_viewHolder_tip);
        TextView btnViewHolderRetry = tipView.findViewById(R.id.base_btn_viewHolder_retry);
        
        if (themeColor != -1) {
            imgViewHolderImage.setColorFilter(themeColor);
            txtViewHolderTip.setTextColor(themeColor);
        }
        
        imgViewHolderImage.setVisibility(VISIBLE);
        if (TextUtils.isEmpty(text)) {
            txtViewHolderTip.setVisibility(GONE);
        } else {
            txtViewHolderTip.setVisibility(VISIBLE);
        }

        if (isShowRetry && showRetryButton) {
            btnViewHolderRetry.setText(retryButtonText);
            btnViewHolderRetry.setVisibility(VISIBLE);
        } else {
            btnViewHolderRetry.setVisibility(GONE);
        }
        
        btnViewHolderRetry.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgress(loadingText, cancelable);
                if (onRetryButtonClickListener!=null){
                    onRetryButtonClickListener.onBackRetryClicked(v);
                }
            }
        });
        
        imgViewHolderImage.setImageResource(resId);
        txtViewHolderTip.setText(text);
        
        showChild(false);
    }
    
    private void showProgress(String msg, boolean cancelable) {
        this.loadingText = msg;
        this.cancelable = cancelable;

        ImageView imgViewHolderImage = tipView.findViewById(R.id.base_img_viewHolder_image);
        TextView txtViewHolderTip = tipView.findViewById(R.id.base_txt_viewHolder_tip);
        TextView btnViewHolderRetry = tipView.findViewById(R.id.base_btn_viewHolder_retry);

        
        imgViewHolderImage.setVisibility(GONE);
        txtViewHolderTip.setVisibility(GONE);
        btnViewHolderRetry.setVisibility(GONE);

        createProgressDialog();
        
        showChild(false);
    }

    private void createProgressDialog() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.z_base_layout_inner_loading, null, false);
        TextView loadingTextView = view.findViewById(R.id.base_tv_loading);
        if (null == loadingText) {
            loadingTextView.setVisibility(GONE);
        } else if ("".equals(loadingText)) {
            loadingTextView.setVisibility(VISIBLE);
            loadingTextView.setText(getContext().getString(R.string.base_txt_common_loading));
        } else {
            loadingTextView.setVisibility(VISIBLE);
            loadingTextView.setText(loadingText);
        }

        progressDialog = new AlertDialog.Builder(getContext(), R.style.Base_Style_Loading)
                .setCancelable(this.cancelable)
                .setView(view)
                .create();
        progressDialog.show();
    }

    private void dismissProgressDialog() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    
    private void refreshViews() {
        childViews = new ArrayList<>();
        for (int i = 0; i < getChildCount(); i++) {
            View childView = getChildAt(i);
            if (childView != tipView) {
                childViews.add(childView);
            }
        }
    }
    
    private void showChild(boolean isShow) {
        for (View child : childViews) {
            if (isShow) {
                child.setVisibility(VISIBLE);
            } else {
                child.setVisibility(GONE);
            }
        }
        if (isShow) {
            tipView.setVisibility(GONE);
        } else {
            tipView.setVisibility(VISIBLE);
        }
    }
    
    @Override
    public void onViewAdded(View child) {
        super.onViewAdded(child);
        refreshViews();
    }
    
    private String getResString(TypedArray typedArray, int id, String defaultStr) {
        String cache = typedArray.getString(id);
        if (cache == null) {
            return defaultStr;
        } else {
            return cache;
        }
    }
    
    public OnRetryButtonClickListener getOnRetryButtonClickListener() {
        return onRetryButtonClickListener;
    }
    
    public HolderView setOnRetryButtonClickListener(OnRetryButtonClickListener onRetryButtonClickListener) {
        this.onRetryButtonClickListener = onRetryButtonClickListener;
        return this;
    }

    public boolean isCancelable() {
        return cancelable;
    }

    @Override
    public void setOnClickListener(OnClickListener l) {
        if (tipView!=null){
            tipView.setOnClickListener(l);
        }
    }

    public interface OnRetryButtonClickListener {
        /**
         * do something when retry icon on clicked
         * @param v view
         * */
        void onBackRetryClicked(View v);
    }
}
